import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, EventEmitter, Injector, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { catchError, throwError } from 'rxjs';
import { environment } from 'src/base/environments/environment';
import { HttpService } from 'src/base/utlis/http.config';
import { CmdSignModel } from 'src/core/module/CmdSignModel';
import { NgsFormCheckboxCompOption, NgsFormOption, NgsFormSelectCompOption, NgsFormUploaderCompOption } from '../ngs-form.config';

@Component({
  selector:'ngs-form',
  templateUrl: './ngs-form.html',
  styleUrls: ['./ngs-form.scss']
})
export class NgsForm implements OnInit {

  protected httpClient: HttpClient;
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private http: HttpService,
    protected injector: Injector,
    private router: Router
  ) { 
    this.httpClient = injector.get(HttpClient);
  }
  
  baseUrl = environment.host;

  myForm!: FormGroup;
  span:number=8;
  

  @Input() option:NgsFormOption | any;
  @Output() onSearch: EventEmitter<any> = new EventEmitter();

  ngOnInit(): void {
    this.myForm = this.fb.group({});
    this.option.components.forEach((component:any) => {
      this.myForm.addControl(component.property+'',new FormControl(null));

      if(component.comp == 'NgsFormSelect'){

        if(Array.isArray(component.dataSource)){
            component.data = component.dataSource;
        }else {
          this.http.exe(component.dataSource).then(res => {
            component.data = res.source;
          });
        }
      }
    });
    if(this.option.column){
      this.span = 24/this.option.column;
    }
  }

  setValue(myforn:any): void{
    let map:any = {};
    this.option.components.forEach((element:any) => {
      if(element.comp == "NgsFormUploader"){
        let str = JSON.parse(myforn[element.property]);
        element.data = str;
      }
      if(element.comp == 'NgsFormSelect'){
        myforn[element.property] = JSON.parse(myforn[element.property]);
      }
      map[element.property] = myforn[element.property];
    });
    this.myForm.setValue(map);
  }


  submitForm(): void {
    this.onSearch.emit(this.myForm.value);
  }

  getValue(){
    let result = this.myForm.value;

    this.option.components.forEach((element:any) => {
      
        if(element.comp == "NgsFormUploader"){
          let urlList:Array<string>  = [];
          if(element.data){
            console.log(element.data)
            element.data.forEach((urlRoot:any) => {
              if(urlRoot.response){
                urlList.push(urlRoot.response);
              }else {
                urlList.push(urlRoot);
              }
            });
            result[element.property] = JSON.stringify(urlList);
          }else{
            if(element.require){
              this.message.error(element.label + "不能为空！");
              throw "form error";
            }
          }
          
        }
        if(element.require && !this.myForm.value[element.property] && this.myForm.value[element.property] !== 0){
            this.message.error(element.label + "不能为空！");
            throw "form error";
        }
    });
    return result;
  }

  resetForm(): void {
    this.myForm.reset({});
    this.onSearch.emit(null);
  }

  /**
   * select 搜索
   */
   selectSerch(event:any,option:NgsFormSelectCompOption){
      if(option.openSerch && option.dataSource){
        let json = JSON.parse(option.dataSource.source);

        json.name = event;
        let cmdSign = new CmdSignModel();

        Object.assign(cmdSign,option.dataSource);
        cmdSign.source = json;

        this.http.exe(cmdSign).then(res => {
          option.data = res.source;
        });
        
      }
   }
   /**
    * chenck 事件
    */
    checnkAction(event: string[],option:NgsFormCheckboxCompOption){
      this.myForm.patchValue({[option.property]:event});
    }

    checkOptions = [
      
    ];

    getAccept(accept:string){
      let nzAccept = "";
      if(!accept){
        return nzAccept;
      }
      if(accept == 'image'){
        return ".jpg,.JPG,.png,.PNG";
      }
      if(accept == 'video'){
        return ".mp4";
      }
      if(accept == 'file'){
        return ".zip";
      }
      return '';
    }

    upload(event:any,uploadOption:NgsFormUploaderCompOption){
      let formData = new FormData();
      console.log(event);
      formData.append("file",event.target.files[0]);
      this.httpClient.post(this.baseUrl+"/oss/api",formData).subscribe((res:any) => {
        uploadOption.data.push(res);
      })
    }

    /**查看图片 和 视频 */
    modal={
      isVisible:false,
      type:1,
      url:''
    }

    handleCancel(){
      this.modal.isVisible = false;
    }

    imageLook(type:number,url:string){
      this.modal = {
        isVisible:true,
        type:type,
        url:url
      }
    }
    del(option:NgsFormUploaderCompOption,i:number){
      option.data.splice(i, 1);
    }

    /**
     * 下拉框高度
     */
    getSelectSize(option:NgsFormSelectCompOption){
      if(option.dsSubLabel || option.dsSubValue){
        return 54;
      }
      return 32;
    }
    /**
     * 下拉框 subValue
     */
    getSeletSubValue(option:NgsFormSelectCompOption,item:any){
      if (typeof option.dsSubValue === "function") {
        return option.dsSubValue(item);
      }
      if(option.dsSubValue) {
        return option.data[option.dsSubValue];
      }
    }


}

